<?php 
class Captcha_model  extends CI_Model {
	
	var $ci;
	var $sessionKey = 'captcha';
	var $isCaseInsensitive = false;
	
	function __construct(){
        parent::__construct();
        $this->ci = &get_instance();
        $this->ci->load->library('session');
    }
    
	public function gen(){
		try{
			$this->ci->session->unset_userdata($this->sessionKey);
			$this->ci->load->library('PhpCaptcha');
			$this->ci->phpcaptcha->SetWidth(120);
			$this->ci->phpcaptcha->SetHeight(30);
			$this->ci->phpcaptcha->SetNumChars(4);
			
			$code = $this->ci->phpcaptcha->Create();
			if(!$code) {
				log_message('error', 'User::genVcode|ERROR|empty code:' . $code);
				return false;
			}
			
			$this->ci->session->set_userdata($this->sessionKey, $code);
			return true;
		}catch(Exception $e){
			log_message('error', 'User::genVcode|ERROR|' . $e);
			return false;
		}
	}
	
	public function validate($vcode){
		if(empty($vcode)){
			return false;
		}
		
		$captcha = $this->ci->session->userdata($this->sessionKey);
		$this->ci->session->unset_userdata($this->sessionKey);
		
		if(!$this->isCaseInsensitive){
			$vcode = strtoupper($vcode);
			$captcha = strtoupper($captcha);
		}
		
		if($vcode != $captcha){
			return false;
		}
		
		return true;
	}
}